#include "../../config.h"
#include "../log.h"

#include <glibmm/i18n.h>

#include "../strfuncs.h"
#include "document.h"

namespace gpyp {
namespace conf {

//========================
// Document
void Document::load() {
  on_preload();
  try {
    std::string path = Glib::filename_from_utf8(file_path_);
    if (Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR)) {
      ConfParser parser(*this);
      parser.parse(file_path_);
    } else {
      log::dbg << "Conf: "
               << format(_("\"%s\" is not a regular file"),
                         file_path_.c_str())
               << log::endl;
    }
  } catch(const Glib::Exception &ex) {
    log::err << "Conf: " << ex.what() << log::endl;
  }
  on_postload();
}
void Document::load(const Source &source) {
  on_preload();
  ConfParser parser(*this);
  parser.parse(source);
  on_postload();
}
void Document::load_default() {
  on_preload();
  on_postload();
}
void Document::save() {
  Element::on_presave();
  if (get_dirty()) {
    try {
      Writer writer;
      std::string path = Glib::filename_from_utf8(file_path_);
      if (writer.open(path)) {
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        writer.new_line();
        version_ = version_current;
        version_->set_dirty(true);
        Element::on_save(writer, false);
      } else {
        log::err << _("failed to open file") << " - " << path << log::endl;
      }
      writer.close();
    } catch(const Glib::Exception &ex) {
      log::err << "Conf: " << ex.what() << log::endl;
    }
  }
}

Document::Document(const Glib::ustring &file_dir,
                   const Glib::ustring &file_name) :
  Element   ("gpyp"),
  file_name_(file_name),
  file_path_(Glib::build_filename(file_dir, file_name)),
  version_  ("version")
{
  add(version_);
}

}/*conf*/
}/*gpyp*/
